
import axios from 'axios';
import Cookies from 'js-cookie'

var HttpsFilter = {

    // install of Vue
    install: function(Vue, options){
        var $this = this;

        if(Vue){
            Vue.prototype.$httpsFilter = $this;
            Vue.httpsFilter = $this;
            
            //原生: XMLHttpRequest.prototype.setRequestHeader
            if(XMLHttpRequest){
                var fOpen = XMLHttpRequest.prototype.open;
                var fHeader = XMLHttpRequest.prototype.setRequestHeader;
                var fSend = XMLHttpRequest.prototype.send;
                XMLHttpRequest.prototype.requestHeaders = {};
                XMLHttpRequest.prototype.openArgs = [];
                XMLHttpRequest.prototype.open = function(...args){
                    this.requestHeaders = {};
                    if(Cookies.get("dep") && args[1].indexOf("dep=") == -1){
                        var _dep = Cookies.get("dep");
                        if(_dep) args[1] = args[1].indexOf("?") != -1 ?  args[1] + "&dep=" + _dep : args[1] + "?dep=" + _dep;
                    }
                    this.openArgs = args;
                    fOpen.apply(this,args);
                };
                XMLHttpRequest.prototype.setRequestHeader = function(name, value){
                    this.requestHeaders[name] = value;
                };
                XMLHttpRequest.prototype.send = function(...args){
                    if(this.openArgs[1].indexOf(".bokecc.com") == -1) this.requestHeaders["X-CSRFToken"] = $this._token();
                    else delete this.requestHeaders["X-CSRFToken"];
                    for(var n in this.requestHeaders){
                        fHeader.apply(this, [n, this.requestHeaders[n]]);
                    }
                    fSend.apply(this, args);
                };
            }
            //原生：fetch二次封装
            // var originFetch = window.fetch;
            // window.fetch = function(...args){
            //     if(args.length == 1){

            //     }else if(args.length >1){

            //     }
            //     originFetch.apply(window, args);
            // };
            
            //vue-resource
            if(Vue.http && Vue.http.interceptors &&  Vue.http.interceptors.push){
                Vue.http.interceptors.push((request, next)  =>{
                    // 在发送请求之前做些什么
                    request.headers.set('X-CSRFToken', $this._token());
                    if(Cookies.get("dep") && request.url.indexOf("dep=") == -1){
                        var _dep = Cookies.get("dep");
                        if(_dep) request.url = request.url.indexOf("?") != -1 ?  request.url + "&dep=" + _dep : request.url + "?dep=" + _dep;
                    }
                    next((response) => {
                        // 对响应数据做点什么
                        return response;
                    });
                });
            }

            //axios-配置
            if(!!axios){

                // 添加请求拦截器
                axios.interceptors.request.use(function (config) {
                    // 在发送请求之前做些什么
                    config.headers['X-CSRFToken'] = $this._token();
                    if(Cookies.get("dep") && config.url.indexOf("dep=") == -1){
                        var _dep = Cookies.get("dep");
                        if(_dep) config.url = config.url.indexOf("?") != -1 ?  config.url + "&dep=" + _dep : config.url + "?dep=" + _dep;
                    }
                    return config;
                }, function (error) {
                    // 对请求错误做些什么
                    return Promise.reject(error);
                });

                // 添加响应拦截器
                axios.interceptors.response.use(function (response) {
                    // 对响应数据做点什么
                    return response;
                }, function (error) {
                    // 对响应错误做点什么
                    return Promise.reject(error);
                });
            }
        }
        
        //jQuery：请求拦截
        if($ && jQuery && $===jQuery){
            //jquery-ajax || ajaxSend
            $(function(){
                //$.ajaxSetup({cache:false});
            });
            $(document).on('ajaxSend', function (event, xhr, settings) {
                    // 在发送请求之前做些什么
                    xhr.setRequestHeader('X-CSRFToken', $this._token());
            });
            var fajax = $.ajax;
            $.ajax = function(options){
                if(Cookies.get("dep") && options.url.indexOf("dep=") == -1){
                    var _dep = Cookies.get("dep");
                    if(_dep) options.url = options.url.indexOf("?") != -1 ?  options.url + "&dep=" + _dep : options.url + "?dep=" + _dep;
                }
                fajax(options);
            }
    
            //jquery-ajax--进一步封装
            $.$http = {
                ajax: function(options){
                    var newOptions  = {};
                    newOptions = $.extend(newOptions, options);
                    newOptions["success"] = function(res){
                        // 对响应数据做点什么
                        options["success"](res);
                    }
                    newOptions["error"] = function(XMLHttpRequest, textStatus, errorThrown){
                        // 对响应错误数据做点什么
                        if(options["error"] && typeof options["error"] === "function") options["error"](XMLHttpRequest, textStatus, errorThrown);
                    }
                    if(Cookies.get("dep") && newOptions.url.indexOf("dep=") == -1){
                        var _dep = Cookies.get("dep");
                        if(_dep) newOptions.url = newOptions.url.indexOf("?") ? newOptions.url + "&dep=" + _dep : newOptions.url + "?dep=" + _dep;
                    }
                    $.ajax(newOptions);
                }
            };
    
            ['get', 'delete', 'head'].forEach(function (method$$1) {
    
                $.$http[method$$1] = function (url, success, err_or) {    
                    var _success = function(res){
                        // 对响应数据做点什么
                        success(res);
                    }
                    var _error = function(XMLHttpRequest, textStatus, errorThrown){
                        // 对响应错误数据做点什么
                        if(err_or && typeof err_or === "function") err_or(XMLHttpRequest, textStatus, errorThrown);
                    }
                    if(Cookies.get("dep") && url.indexOf("dep=") == -1){
                        var _dep = Cookies.get("dep");
                        if(_dep) url = url.indexOf("?") ? url + "&dep=" + _dep : url + "?dep=" + _dep;
                    }
                    return $.ajax({url: url, type: method$$1, success: _success, error: _error});
                };
    
            });
    
            ['post', 'put', 'patch'].forEach(function (method$$1) {
    
                $.$http[method$$1] = function (url, body, success, err_or) {
    
                    var _success = function(res){
                        // 对响应数据做点什么
                        success(res);
                    }
    
                    var _error = function(XMLHttpRequest, textStatus, errorThrown){
                        // 对响应错误数据做点什么
                        if(err_or && typeof err_or === "function") err_or(XMLHttpRequest, textStatus, errorThrown);
                    }
                    if(Cookies.get("dep") && url.indexOf("dep=") == -1){
                        var _dep = Cookies.get("dep").split("/")[1];
                        if(_dep) url = url.indexOf("?") ? url + "&dep=" + _dep : url + "?dep=" + _dep;
                    }
                    return $.ajax({url: url, type: method$$1, data: body, success: _success, error: _error});
                };
    
            });
        }
    },
    scheme: function() {
        return window.location.protocol === 'http:' ? 'http:' : 'https:';
    },
    getGlobal: function(){
        if(typeof globalThis !== 'undefined'){return globalThis;}
        if(typeof self !== 'undefined'){return self;}
        if(typeof window !== 'undefined'){return window;}
        if(typeof global !== 'undefined'){return global;}
        throw new Error('unable to locate global object');
    },
    _ajax: function(url, data){//打点event

        var $this = this;

        if(!data){
            var d1 = {};
            if(url.indexOf("?") != -1){
                d1 = $this.parseQueryUrl(url);
                url = url.split("?")[0];
            }
            data = d1;
        }
        data = $this._parseObject(data);//解析data，瘦身
        var endData = {
            event_type: url,
            page: window.location.href,
            event: data
        };

        var apiUrl = $this.scheme() + "//cloudlog.xuetangx.com/event";

        function _(err, obj){}

        var _event = encodeURIComponent(JSON.stringify(endData.event));
        apiUrl += '?url=' + endData.event_type + '&page=' + endData.page + '&event=' + _event;
        $this.jsonp(apiUrl, {
            param: 'callback'
        }, function(err, obj) {
            if (err) return _(err);
            _(null, {
                url: endData.event_type,
                body: obj
            });
        });

    },
    /**
     * JSONP handler
     *
     * Options:
     *  - param {String} qs parameter (`callback`)
     *  - timeout {Number} how long after a timeout error is emitted (`60000`)
     *
     * @param {String} url
     * @param {Object|Function} optional options / callback
     * @param {Function} optional callback
     */
    jsonp: function(url, opts, fn){
        if ('function' == typeof opts) {
            fn = opts;
            opts = {};
        }
        if (!opts) opts = {};

        var prefix = opts.prefix || '__jp';
        var param = opts.param || 'callback';
        var timeout = null != opts.timeout ? opts.timeout : 6000;
        var enc = encodeURIComponent;
        var target = document.getElementsByTagName('script')[0] || document.head;
        var script;
        var timer;

        var id = prefix + new Date().getTime();

        if (timeout) {
            timer = setTimeout(function() {
                cleanup();
                if (fn) fn(new Error('Timeout'));
            }, timeout);
        }

        function cleanup() {
            script.parentNode.removeChild(script);
            delete window[id];
        }

        window[id] = function(data) {
            if (timer) clearTimeout(timer);
            cleanup();
            if (fn) fn(null, data);
        };

        // add qs component
        url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id);
        url = url.replace('?&', '?');

        // create script
        script = document.createElement('script');
        script.src = url;
        target.parentNode.insertBefore(script, target);
    },

    _parseObject: function(data){//给data，瘦身
        var $this = this;
        var arrayBufferTypes = ["arraybufer", "int8array", "uint8array", "int16array", "uint16array", "int32array", "uint32array", "float32array", "float64array"];
        var _data = null;
        var _type = $this._type(data)

        if(_type == "object"){
            _data = {};
            for(var key in data){
                var _val = data[key];
                _data[key] = $this._parseObject(_val);
            }
        }else if(_type == "string" && data.indexOf("data:image/") != -1 && data.indexOf(";base64,") != -1){//base64-image处理
            var subTop = data.split(";base64,")[0] + ";base64,";
            data = data.split(";base64,")[1];
            var l = data.length,i;
            var blen = 0;
            for(i=0; i<l; i++) {
                if ((data.charCodeAt(i) & 0xff00) != 0) {
                    blen ++;
                }
                blen ++;
            }
            _data = subTop + blen + "bytes";
        }else if(_type == "string"){
            var l = data.length,i;
            var blen = 0;
            for(i=0; i<l; i++) {
                if ((data.charCodeAt(i) & 0xff00) != 0) {
                    blen ++;
                }
                blen ++;
            }
            if(blen > 100) _data = "String@" + blen + "bytes";
            else _data = data.toString();
        }else if(_type == "array" || _type == "arguments"){
            _data = [];
            if(data.length > 0){
                for(var k=0; k< data.length; k++){
                    var __val = data[k];
                    _data[k] = $this._parseObject(__val);
                }
            }
        }else if(arrayBufferTypes.indexOf(_type) > -1){
            _data = _type + "@" + data.byteLength + "bytes";
        }else if(_type == "undefined"){
            _data = "undefined";
        }else if(_type == "null"){
            _data = "null";
        }else if(_type == "nan"){
            _data = "NaN";
        }else _data = data.toString();

        return _data;
    },
    _type: function(val){
        switch (toString.call(val)) {
            case '[object Date]':
                return 'date';
            case '[object RegExp]':
                return 'regexp';
            case '[object Arguments]':
                return 'arguments';
            case '[object Array]':
                return 'array';
            case '[object ArrayBuffer]':
                return 'arraybufer';
            case '[object Int8Array]':
                return 'int8array';
            case '[object Uint8Array]':
                return 'uint8array';
            case '[object Int16Array]':
                return 'int16array';
            case '[object Uint16Array]':
                return 'uint16array';
            case '[object Int32Array]':
                return 'int32array';
            case '[object Uint32Array]':
                return 'uint32array';
            case '[object Float32Array]':
                return 'float32array';
            case '[object Float64Array]':
                return 'float64array';
            case '[object Error]':
                return 'error';
        }

        if (val === null) return 'null';
        if (val === undefined) return 'undefined';
        if (val !== val) return 'nan';
        if (val && val.nodeType === 1) return 'element';

        val = val.valueOf ? val.valueOf() : Object.prototype.valueOf.apply(val)

        return typeof val;
    },
    // 生成参数
    buildUrl: function (obj) {
        var arr = [];
        for( var i in obj ){
            arr.push(i + '=' + encodeURIComponent(obj[i]));
        }
        return arr.join('&');
    },
    getCookieValue: function(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                //var cookie = jQuery.trim(cookies[i]);
                var cookie = cookies[i].replace(/\s+/g, "");
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    },
    _token: function(key, isJSON){
        key = key ? key : 'csrftoken';
        var converter = function(){};
        if (typeof document === 'undefined') {
            return;
        }
        var jar = {};
        var cookies = document.cookie ? document.cookie.split('; ') : [];
        var i = 0;
        
        for (; i < cookies.length; i++) {
            var parts = cookies[i].split('=');
            var cookie = parts.slice(1).join('=');
        
            if (!isJSON && cookie.charAt(0) === '"') {
            cookie = cookie.slice(1, -1);
            }
        
            try {
            var name = parts[0].replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
            cookie = (converter.read || converter)(cookie, name) || cookie.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
            if (isJSON) {
                try {
                cookie = JSON.parse(cookie);
                } catch (e) {}
            }
        
            jar[name] = cookie;
        
            if (key === name) {
                break;
            }
            } catch (e) {}
        }
        
        return key ? jar[key] : jar;
    },
    parseQueryUrl: function(url){
        var url = url || window.location.href;
        var reg_url =/^[^\?]+\?([\w\W]+)$/,
            arr_url = reg_url.exec(url),
            reg_para=/([^&=]+)=([\w\W]*?)(&|$)/g, //g is very important
            ret = {};
        if(arr_url && arr_url[1]){
            if(url.indexOf("#") != -1){
                if(arr_url[1].indexOf("#") != -1){
                    ret['hash'] = arr_url[1].substr(arr_url[1].indexOf("#")+1);
                    arr_url[1] = arr_url[1].substring(0, arr_url[1].indexOf("#"));
                }else{
                    ret['hash'] = url.substr(url.indexOf("#")+1).split("?")[0];
                }
                var hashQuery = reg_url.exec(ret['hash']);
                if(hashQuery && hashQuery[1]){
                    var _str_para = hashQuery[1], _result;
                    ret['hash'] = ret['hash'].split("?")[0];
                    while((_result = reg_para.exec(_str_para)) != null){
                        ret[_result[1]] = _result[2];
                    }
                }
            }
            var str_para = arr_url[1],result;
            while((result = reg_para.exec(str_para)) != null){
                ret[result[1]] = result[2];
            }
        }
        return ret;
    }
};
export default HttpsFilter;
  